import React from 'react'
import { connect } from 'react-redux'
import { messages } from "share/common";
import { Form, Input, Switch, Button, message, Spin, Radio, Popover, Icon, Select, Checkbox } from 'antd'
import approveSuggestService from 'containers/setting/approve-suggest/approve-suggest.service'
const CheckboxGroup = Checkbox.Group;
const { TextArea } = Input;
const FormItem = Form.Item;
const RadioGroup = Radio.Group;
const Option = Select.Option;
import errorMessage from "share/errorMessage";
import "styles/setting/workflow-config/new-workflow-config.scss"
import Priority from 'components/template/priority'
import FloatDays from 'containers/application-setting/comp/floatDays'
const formItemLayout = {
  labelCol: { span: 6 },
  wrapperCol: { span: 14, offset: 1 },
};

class NewFpConfig extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      isShowLoading: false,
      configFp: [],
      configFunctionProfile: {},
      levelConfig: {},
      saveLoading: false,
    }
  }

  componentDidMount() {
    let { apiService, id, configFp } =  this.props.params;
    let { tenant } = this.props;
    this.setState({ isShowLoading: true });
    //查询默认规则或者规则详情
    apiService({ id: id }).then(res => {
      let defaultValue = {};
      if (res && res.data) {
        if (id) {
          defaultValue = {
            levelCode: res.data.levelCode,
            levelOrgName: res.data.levelOrgName || res.data.levelName,
            levelOrgId: res.data.levelOrgId
          };
        } else {
          let { authPolicyAll } = this.props;
          res.data.id = null;
          if(authPolicyAll){
            defaultValue = {
              levelCode: 'TENANT',
              levelOrgName: tenant.tenantName,
              levelOrgId: tenant.id
            }
          }
        }
        this.setState({ isShowLoading: false, levelConfig: defaultValue, configFp, configFunctionProfile: res.data }, this.processSelectData);
      }
    }).catch(res => {
      this.setState({ isShowLoading: false })
    })
  }

  //处理配置type为select类型的可选范围
  processSelectData = () => {
    const { dataService } =  this.props.params;
    const { levelConfig, configFp } = this.state;
    configFp.forEach(config => {
      config.groupList.forEach(groupItem => {
        if (groupItem.type === 'select' && groupItem.dependCode && levelConfig && levelConfig.levelCode && levelConfig.levelOrgId) {
          groupItem.dataLoading = true;
          this.setState({configFp});
          dataService(groupItem.url, {
            page: 0,
            size: 1000,
            levelCode: levelConfig.levelCode,
            levelOrgId: levelConfig.levelOrgId
          }).then(res => {
            groupItem.dataList = res.data || [];
            groupItem.dataLoading = false;
            this.setState({configFp});
          }).catch(err => {
            groupItem.dataLoading = false;
            this.setState({configFp});
          });
        }
      });
    });
  };

  //清空配置type为select类型的可选范围以及已选值
  clearSelectData = (isClearDataList) => {
    const { levelConfig, configFp } = this.state;
    const { setFieldsValue } = this.props.form;
    let setData = {};
    configFp.forEach(config => {
      config.groupList.forEach(groupItem => {
        if (groupItem.type === 'select' && groupItem.dependCode) {
          if (isClearDataList) {
            groupItem.dataList = [];
          }
          setData[groupItem.fpCode] = undefined;
        }
      });
    });
    isClearDataList && this.setState({configFp});
    setFieldsValue(setData);
  };

  //保存
  handleSave = e => {
    e.preventDefault();
    const { form } = this.props;
    const { levelConfig, configFunctionProfile } = this.state;
    if (levelConfig && !levelConfig.levelOrgId) {
      message.error(messages('request-1.key723')/*请选择所属组织*/);
      return;
    }
    form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        const { head } = this.state;
        let params = Object.assign({}, head, configFunctionProfile, values, levelConfig);
        this.setState({
          saveLoading: true,
        });
        let { saveApiService } =  this.props.params;
        saveApiService(params).then(res => {
          this.setState({ saveLoading: false });
          this.props.close(true);
        }).catch(e => {
          this.setState({ saveLoading: false });
          errorMessage(e.response)
        })

      }
    })
  };

  handleChangePriority = res => {
    const { levelConfig } = this.state;
    let isChange = false;
    if (res && res.levelOrgId !== levelConfig.levelOrgId) {
      isChange = true;
    }
    if (res) {
      this.setState({ levelConfig: res }, () => {
        isChange && this.clearSelectData(false); //刷新dataList在processSelectData操作
        isChange && this.processSelectData();
      });
    } else {
      this.setState({ levelConfig: {} }, () => this.clearSelectData(true));
    }
  };

  handleChangeExt = (e, code) => {
    let { configFunctionProfile } =this.state;
    if(code.isHasExtra){
      configFunctionProfile[code.fpCode] = e.target.value;
      this.setState({ configFunctionProfile });
    }
  };

  renderConfigItem = groupItem => {
    const { getFieldDecorator,getFieldValue } = this.props.form;
    let { configFunctionProfile, levelConfig } = this.state;
    switch(groupItem.type) {
      case 'select':
        return <div className='normal-width'>
          {getFieldDecorator(groupItem.fpCode + '', {
            initialValue: configFunctionProfile[groupItem.fpCode] || undefined
          })(
            <Select
              allowClear
              disabled={groupItem.dataLoading || (groupItem.dependCode && !levelConfig.levelOrgId)}
              optionFilterProp="children"
              getPopupContainer={triggerNode => triggerNode.parentNode}
              placeholder={messages('common.select')/*请选择*/}
            >
              {groupItem.dataList.map(item => {
                return <Option key={item.levelOID}>{item.levelName}</Option>
              })}
            </Select>
          )}
        </div>
        break;
      case 'comp-float-days':
        return <div className='normal-width'>
          {getFieldDecorator(groupItem.fpCode + '', {
            initialValue: configFunctionProfile[groupItem.fpCode]
          })(
            <FloatDays
              parser={value => {
                let result = {
                  range: 'DEFAULT',
                  value: undefined
                };
                if (typeof value === 'number') {
                  result = {
                    range: value === 0 ? 'CURRENT' : (value > 0 ? 'AFTER' : 'BEFORE'),
                    value: Math.abs(value)
                  }
                }
                return result;
              }}
              formatter={obj => {
                let result = undefined;
                if (obj.range === 'AFTER' && obj.value) {
                  result = obj.value;
                }
                if (obj.range === 'BEFORE' && obj.value) {
                  result = -obj.value;
                }
                if (obj.range === 'CURRENT') {
                  result = 0;
                }
                return result;
              }}
            />
          )}
        </div>
        break;
      case 'checkBox':
        return <div>
          {getFieldDecorator(groupItem.fpCode + '', {
            initialValue: configFunctionProfile[groupItem.fpCode]
          })(
            <CheckboxGroup options={groupItem.options}/>
          )}
        </div>
        break;
      default:
        return <div>
          {getFieldDecorator(groupItem.fpCode + '', {
            initialValue: configFunctionProfile[groupItem.fpCode]
          })(
            <RadioGroup
              disabled={!!configFunctionProfile.readOnly}
              onChange={e => this.handleChangeExt(e, groupItem)}
              options={groupItem.options}
            />
          )}
        </div>
        break;
    }
  }

  renderConfigExtraItem = groupItem => {
    let { configFunctionProfile } = this.state;

    switch(groupItem.exTraCondition.type) {
      case 'checkBox':
        return <CheckboxGroup options={groupItem.exTraCondition.options}/>
        break;
      case 'textArea':
        const { getFieldValue } = this.props.form;
        if (getFieldValue('confirmType') === '1') {
          return <TextArea className="text-area"/>
        } else {
          return <div />;
        }
        break;
      default:
        return <RadioGroup
          disabled={!!configFunctionProfile.readOnly}
          options={groupItem.exTraCondition.options}
        />
        break
    }
  };


  renderConfigFp = config => {
    const { getFieldDecorator,getFieldValue } = this.props.form;
    let { configFunctionProfile, levelConfig } = this.state;
    return <div className="radio-list-wrap">
      {config.groupList.filter(item => !item.isHide).map(groupItem => {
        let isShowExtra =groupItem.isHasExtra && configFunctionProfile[groupItem.fpCode] === groupItem.isShowExtra;//默认值
        return <div
          key={groupItem.fpCode}
          className={isShowExtra ? 'extra-fp' : ''}>
          <FormItem
            className="function-profile-list"
            extra={groupItem.description}
            label={(
              <span>{groupItem.fpName}&nbsp;
                {groupItem.tooltipInfo && (
                  <Popover content={(groupItem.tooltipInfo)}>
                    <Icon type="info-circle-o" className='font-description' />
                  </Popover>
                )}
              </span>
            )}
            {...this.props.params.formItemLayout || formItemLayout}
          >
            {groupItem.info &&
            <Popover content={groupItem.info}>
              <Icon type="info-circle-o" className='font-description' style={{ marginRight: '10px' }}/>
            </Popover>
            }
            {this.renderConfigItem(groupItem)}
          </FormItem>
          { isShowExtra && groupItem.exTraCondition &&
          <FormItem className={`function-profile-list`}
                    extra={groupItem.exTraCondition.description}
                    label={groupItem.exTraCondition.fpName} {...this.props.params.formItemLayout || formItemLayout}>
            {getFieldDecorator(groupItem.exTraCondition.fpCode + '', {
              initialValue: configFunctionProfile[groupItem.exTraCondition.fpCode] || groupItem.exTraCondition.initialValue
            })(
              this.renderConfigExtraItem(groupItem)
            )}
          </FormItem>}

          {/* feature 13283 当选择不同option时显示不同的extra，则把description设置成object，对应的key设置成option的value */}
          {isShowExtra && groupItem.exTraConditionList && !!groupItem.exTraConditionList.length && (
            <div>
              {groupItem.exTraConditionList.map(exTraConditionItem => {
                return (
                  <FormItem className={`function-profile-list`}
                            extra={(exTraConditionItem.description && typeof(exTraConditionItem.description) === 'object')
                              ? exTraConditionItem.description[Number(getFieldValue(exTraConditionItem.fpCode) || configFunctionProfile[exTraConditionItem.fpCode])] : exTraConditionItem.description}
                            label={exTraConditionItem.fpName} {...this.props.params.formItemLayout || formItemLayout}>
                    {getFieldDecorator(exTraConditionItem.fpCode + '', {
                      initialValue: configFunctionProfile[exTraConditionItem.fpCode] || exTraConditionItem.initialValue
                    })(
                      this.renderConfigExtraItem({exTraCondition: exTraConditionItem})
                    )}
                  </FormItem>
                )
              })}
            </div>
          )}
        </div>;
      })}
    </div>
  };

  render() {
    const { saveLoading, configFp, isShowLoading, configFunctionProfile, levelConfig } = this.state;
    const { getFieldDecorator } = this.props.form;
    let tenantMode = this.props.authPolicyAll;
    return (
      <div className="new-workflow-config">
        <Form className="new-form">
          <Spin spinning={isShowLoading}>
            <FormItem label={messages('common.column.status')/*状态*/} {...this.props.params.formItemLayout || formItemLayout}>
              {getFieldDecorator('enabled', {
                initialValue: configFunctionProfile.id ? configFunctionProfile.enabled : true,
                valuePropName: 'checked'
              })(
                <Switch disabled={configFunctionProfile.readOnly}/>
              )}
            </FormItem>
            {!isShowLoading && <Priority
              style={{ marginLeft: 0 }}
              onChange={this.handleChangePriority}
              formItemLayout={this.props.params.formItemLayout || formItemLayout}
              top={configFunctionProfile.id ? configFunctionProfile.levelCode : (tenantMode ? 'TENANT' : 'COMPANY')}
              showCompanyComponent={false}
              showCompany
              defaultValue={(configFunctionProfile.id || tenantMode ) ? levelConfig : null}
              disabled={!!(configFunctionProfile.id || configFunctionProfile.readOnly)}
              companyProps={{
                single: true,
                disabled: !!(configFunctionProfile.id || configFunctionProfile.readOnly)
              }}
            />}
            {
              configFp.map(config => {
                return !!config.groupList.filter(item => !item.isHide).length ? (
                  <div key={config.moduleName} className="config-wrap">
                    {config.moduleName && <h3 className="sub-title">
                      {config.moduleName}
                    </h3>}
                    { this.renderConfigFp(config)}
                  </div>
                ) : <div />
              })
            }
          </Spin>
          <div className="slide-footer">
            {!configFunctionProfile.readOnly && <Button
              type="primary"
              onClick={this.handleSave}
              style={{ margin: '0px 10px' }}
              loading={saveLoading}
            >
              {messages('common.ok')/*确定*/}
            </Button>}
            <Button onClick={this.props.close}>{messages('common.cancel')/*取消*/}</Button>
          </div>
        </Form>
      </div>
    )
  }
}

function mapStateToProps(state) {
  return {
    tenant: state.login.tenant,
    tenantMode: state.main.tenantMode,
    authPolicyAll: state.main.authPolicyAll,
    currentMenuPermission: state.main.currentMenuPermission,
  }
}
const wrappedNewFpConfig = Form.create()(NewFpConfig);
export default connect(mapStateToProps)(wrappedNewFpConfig);
